package com.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author: create by God of SJF
 * @version: v1.0
 * @description: com.config
 * @date:2021/9/13
 */
@Component
public class ShardingDictionaries {

    @Autowired
    RedisTemplate redisTemplate;

    static Map<String, String> shardingMap = new HashMap();

    static Map<String, String> shardingDetailMap = new HashMap();

    static final String SHARDING_DICTIONARIES_KEY = "Dictionaries";

    static final String SHARDING_DETAIL_DICTIONARIES_KEY = "DetailDictionaries";

    public void flush() {
        Set<Object> set = redisTemplate.opsForHash().keys(SHARDING_DICTIONARIES_KEY);
        if (!CollectionUtils.isEmpty(set)) {
            set.stream().forEach(o -> {
                String inKey = (String) o;
                String value = (String) redisTemplate.opsForHash().get(SHARDING_DICTIONARIES_KEY, inKey);
                shardingMap.put(inKey, value);
            });
        }
    }

    public void flush2() {
        Set set = redisTemplate.opsForHash().keys(SHARDING_DETAIL_DICTIONARIES_KEY);
        if (!CollectionUtils.isEmpty(set)) {
            set.stream().forEach(o -> {
                String inKey = (String) o;
                String value = (String) redisTemplate.opsForHash().get(SHARDING_DETAIL_DICTIONARIES_KEY, inKey);
                shardingDetailMap.put(inKey, value);
            });
        }
    }

    public synchronized String key(String findKey) {
        if (CollectionUtils.isEmpty(shardingMap)) {
            flush();
        }
        return shardingMap.get(findKey);
    }

    public synchronized String detailKey(String findKey) {
        if (CollectionUtils.isEmpty(shardingDetailMap)) {
            flush2();
        }
        return shardingDetailMap.get(findKey);
    }


    public ShardingDictionaries() {
        RedisTemplate<String, String> template = new RedisTemplate<>();
        JedisConnectionFactory fac = new JedisConnectionFactory(new JedisPoolConfig());
        JedisShardInfo shardInfo = new JedisShardInfo("localhost", 6379);
        fac.setShardInfo(shardInfo);
        template.setConnectionFactory(fac);
        template.setDefaultSerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        this.redisTemplate = template;
    }
}
